﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class _56uuLogin : LoginImplBase
    {
        public _56uuLogin() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            string loginurl = "http://www.56uu.com/login.html";
            string data = String.Format("rnd={0}&act=ajlogin&getlog=ptlogin&username={1}&password={2}&save_id=1",
                _rand.NextDouble(), _username, _password);
            HttpResult resp = TransferMgr.doPostPure(loginurl, data, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            string retstr = resp.getContent();

            if (!retstr.Contains("member_id"))
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            // 查找serverid字符串
            string gamelisturl = "http://as.56uu.com/server_list.html";
            resp = TransferMgr.doGetPure(gamelisturl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetServerList; return result; }

            string content = resp.getContent();
            string district_name = String.Format("(\\[{0}\\]|56uu{0}服)", _acc.ServerId);
            Regex re = new Regex(String.Format("<a.*href=[\"']+?([^\"']*?)[\"']+?.*>.*?{0}.*?</a>", district_name));
            Match m = re.Match(content);
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInFindingGameUrl; return result; }

            string redirecturl = m.Groups[1].Value;
            resp = TransferMgr.doGetPure(redirecturl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }
            content = resp.getContent();
            re = new Regex("<frame src=[\"']+?(.*?)[\"']+?.*");
            m = re.Match(content);
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }

            string gameurl = m.Groups[1].Value;
            processStartGame(gameurl, result, ref cookies);
            return result;
        }
    }
}
